import { Inject, Injectable } from '@nestjs/common';
import { ListJobLogDto } from './dto/create-job.dto';
import { ResultData } from 'src/common/utils/result';
import { ExportTable } from 'src/common/utils/export';
import { Response } from 'express';
import { PrismaService } from "@/module/common/prisma/prisma.service";
import { JobLog } from '@/module/common/prisma/client';
@Injectable()
export class JobLogService {
    @Inject()
    private readonly prisma: PrismaService
    constructor() { }

    /**
     * 查询任务日志列表
     */
    async list(query: ListJobLogDto) {
        const { pageSize, pageNum, jobName, jobGroup, status } = query;

        const skip = pageSize && pageNum ? pageSize * (pageNum - 1) : 0;
        const take = +pageSize || 10;

        const where: any = {};
        if (query.jobName) {
            where.jobName = { contains: jobName }
        }

        if (query.jobGroup) {
            where.jobGroup = jobGroup
        }
        if (query.status) {
            where.status = status
        }
        if (query?.beginTime && query?.endTime) {
            where.createTime = {
                gte: new Date(query.beginTime),
                lte: new Date(query.endTime),
            }
        }
        const [list, total] = await Promise.all([
            this.prisma.jobLog.findMany({
                where,
                skip,
                take,
                orderBy: {
                    createTime: 'desc',
                },
            }),
            this.prisma.jobLog.count({ where }),
        ]);

        return ResultData.ok({
            list,
            total,
        });

    }

    /**
     * 添加任务日志
     */
    async addJobLog(jobLog: Partial<JobLog>) {
        try {
            const log = await this.prisma.jobLog.create({
                data: jobLog as JobLog,
            });
            return ResultData.ok(log);
        } catch (error) {
            console.error('Error adding job log:', error);
            throw error;
        }
    }

    /**
     * 清空日志
     */
    async clean() {
        try {
            // 使用 deleteMany 清空表数据
            await this.prisma.jobLog.deleteMany({});
            return ResultData.ok();
        } catch (error) {
            console.error('Error cleaning job logs:', error);
            throw error;
        }
    }

    /**
     * 导出调度日志为xlsx文件
     * @param res
     */
    async export(res: Response, body: ListJobLogDto) {
        delete body.pageNum;
        delete body.pageSize;
        const list = await this.list(body);
        const options = {
            sheetName: '调度日志',
            data: list.data.list,
            header: [
                { title: '日志编号', dataIndex: 'jobLogId' },
                { title: '任务名称', dataIndex: 'jobName' },
                { title: '任务组名', dataIndex: 'jobGroup' },
                { title: '调用目标字符串', dataIndex: 'invokeTarget' },
                { title: '日志信息', dataIndex: 'jobMessage' },
                { title: '执行时间', dataIndex: 'createTime' },
            ],
            dictMap: {
                status: {
                    '0': '成功',
                    '1': '失败',
                },
                jobGroup: {
                    SYSTEM: '系统',
                    DEFAULT: '默认',
                },
            },
        };
        ExportTable(options, res);
    }
}
